﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orchard.Environment.Extensions;
using Orchard.Events;
using Downplay.Audit.Services;
using Orchard.Localization;
using Orchard.ContentManagement;

namespace Downplay.Audit.Rules
{
    public interface IActionProvider : IEventHandler
    {
        void Describe(dynamic describe);
    }

    [OrchardFeature("Downplay.Audit.Rules")]
    public class AuditActions : IActionProvider
    {
        private readonly IAuditService _auditService;

        public AuditActions(
            IAuditService auditService
            ) {

            _auditService = auditService;

            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(dynamic describe)
        {
            Func<dynamic, LocalizedString> display = context => T("Create an Audit record for an event");

            describe.For("Auditing", T("Auditing"), T("Audit"))
                .Element("AuditEvent", T("Audit an event"), T("Creates an Audit record for the triggered event."),
                    (Func<dynamic, bool>)Audit, display, "ActionAudit");
        }

        private bool Audit(dynamic context)
        {
            var content = context.Tokens["Content"] as IContent;
            var code = context.Properties["AuditCode"] as String;
            // TODO: Automatically use event name (if it gets made available)

            var data = context.Properties.ContainsKey("AuditData") ? (context.Properties["AuditData"] as String) : "";
            _auditService.CreateAudit(code, content, true, data);
            return true;
        }
    }
}
